import subprocess


# run
def runTest():
    # 执行Linux命令
    subprocess.run(["ls", "-al"])
    subprocess.run(["ls", "-al"], shell=True)
    subprocess.run(["ls", "-al"], shell=True, check=True)

    # 执行dos命令
    # subprocess.run(["cmd", "/C", "dir D:\app"])

    # 运行 .py文件，无须加 cmd.exe
    # subprocess.run(["python", "demo.py", "5"]) 其中5为参数


# pipe
def pipeTest():
    cp1 = subprocess.run(["ls", "-al"], stdout=subprocess.PIPE)
    print(cp1.stdout.decode("utf-8"))


# popen api使用
def popenTest():
    p = subprocess.Popen("ls -al", shell=True)
    print(p.returncode)  # None
    p.wait()
    print(p.returncode)

    # 支持context
    # with Popen(["ifconfig"], stdout=PIPE) as proc:
    #     log.write(proc.stdout.read())


if __name__ == "__main__":
    popenTest()
